const { app } = require('electron');
const fs = require('fs');
const path = require('path');

class AutoStartManager {
  constructor() {
    this.appName = '项目管理系统';
    this.registryKey = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run';
  }

  /**
   * 检查是否已设置开机自启动
   * @returns {boolean}
   */
  isAutoStartEnabled() {
    try {
      const { execSync } = require('child_process');
      const result = execSync(`reg query "${this.registryKey}" /v "${this.appName}"`, { encoding: 'utf8' });
      return result.includes(this.appName);
    } catch (error) {
      return false;
    }
  }

  /**
   * 启用开机自启动
   * @returns {boolean}
   */
  enableAutoStart() {
    try {
      const { execSync } = require('child_process');
      const exePath = app.getPath('exe');
      const command = `reg add "${this.registryKey}" /v "${this.appName}" /t REG_SZ /d "${exePath}" /f`;
      execSync(command);
      return true;
    } catch (error) {
      console.error('启用开机自启动失败:', error);
      return false;
    }
  }

  /**
   * 禁用开机自启动
   * @returns {boolean}
   */
  disableAutoStart() {
    try {
      const { execSync } = require('child_process');
      const command = `reg delete "${this.registryKey}" /v "${this.appName}" /f`;
      execSync(command);
      return true;
    } catch (error) {
      console.error('禁用开机自启动失败:', error);
      return false;
    }
  }

  /**
   * 切换开机自启动状态
   * @returns {boolean} 切换后的状态
   */
  toggleAutoStart() {
    if (this.isAutoStartEnabled()) {
      this.disableAutoStart();
      return false;
    } else {
      this.enableAutoStart();
      return true;
    }
  }

  /**
   * 获取当前应用的可执行文件路径
   * @returns {string}
   */
  getAppPath() {
    return app.getPath('exe');
  }
}

module.exports = AutoStartManager; 